import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:path_provider/path_provider.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_09_game/config/app_config.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/pages/main/model_app_package.dart';
import 'package:flutter_09_game/widgets/button/common_button.dart';
import 'package:flutter_09_game/widgets/image/auto_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:flutter_09_game/http/http_manager.dart';
import 'package:flutter_09_game/utils/loading/loading_utils.dart';

class WidgetDialogPackage extends StatefulWidget {
  // const WidgetDialogPackage({super.key});
  const WidgetDialogPackage({super.key, required this.appPackage});

  static String name = 'WidgetDialogPackage';

  final ModelAppPackage appPackage;

  /// 显示公告弹窗
  static Future<void> show({required ModelAppPackage appPackage}) async {
    // GetBuilder
    return await Get.dialog(
      WidgetDialogPackage(
        appPackage: appPackage,
      ),
      barrierDismissible: false,
      name: WidgetDialogPackage.name,
      barrierColor: Colors.black.withOpacity(0.5),
    );
  }

  @override
  State<WidgetDialogPackage> createState() => _WidgetDialogPackageState();
}

class _WidgetDialogPackageState extends State<WidgetDialogPackage> {
  bool isDownload = false;
  double downloadProgress = 0.0;
  int downloadPercent = 0;
  CancelToken? cancelToken;
  String? downloadFilePath;

  @override
  void dispose() {
    cancelToken?.cancel();
    super.dispose();
  }

  /// 开始下载并安装
  Future<void> _startDownloadAndInstall() async {
    try {
      if (Platform.isIOS) {
        // iOS 直接打开下载链接
        final String ipaUrl =
            '${AppConfig.baseImage}${widget.appPackage.ipaDownload ?? ''}';
        // final bool canLaunch = await canLaunchUrlString(ipaUrl);
        // if (canLaunch) {
        await launchUrlString(ipaUrl, mode: LaunchMode.externalApplication);
        // Get.back();
        // } else {
        //   LoadingUtils.showToast('无法打开下载链接');
        // }
      } else if (Platform.isAndroid) {
        // Android 下载并安装
        if (mounted) {
          setState(() {
            isDownload = true;
            downloadProgress = 0.0;
            downloadPercent = 0;
          });
        }

        // 创建取消令牌
        cancelToken = CancelToken();

        // 获取临时目录
        final tempDir = await getTemporaryDirectory();

        // 构建文件名
        String fileName =
            widget.appPackage.apkDownload?.split('/').last ?? 'app-release.apk';
        if (!fileName.endsWith('.apk')) {
          fileName = 'app-release.apk';
        }

        // 构建文件保存路径
        downloadFilePath = '${tempDir.path}/$fileName';

        // 构建完整下载URL
        final String apkUrl =
            '${AppConfig.baseImage}${widget.appPackage.apkDownload ?? ''}';

        // 开始下载
        final response = await HttpManager().download(
          url: apkUrl,
          savePath: downloadFilePath!,
          cancelToken: cancelToken,
          onReceiveCallback: (received, total) {
            if (total > 0 && mounted) {
              setState(() {
                downloadProgress = received / total;
                downloadPercent = (downloadProgress * 100).toInt();
              });
            }
          },
        );

        // 下载完成处理
        if (response.isSuccess && downloadFilePath != null) {
          await _installApk(downloadFilePath!);
        } else {
          if (mounted) {
            setState(() {
              isDownload = false;
            });
          }
          LoadingUtils.showToast(LocaleKeys.downloadFailed.tr);
        }
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          isDownload = false;
        });
      }
      LoadingUtils.showToast(LocaleKeys.operationFailed.tr);
    }
  }

  /// 安装APK
  Future<void> _installApk(String filePath) async {
    try {
      final result = await InstallPlugin.install(filePath);
      if (result['isSuccess'] == true) {
        LoadingUtils.showToast(LocaleKeys.startInstall.tr);
        // Get.back();
      } else {
        LoadingUtils.showToast(LocaleKeys.installFailed.tr);
        if (mounted) {
          setState(() {
            isDownload = false;
          });
        }
      }
    } catch (e) {
      LoadingUtils.showToast(LocaleKeys.installError.tr);
      if (mounted) {
        setState(() {
          isDownload = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
        canPop: false,
        onPopInvokedWithResult: (canPop, value) {},
        child: Center(
            child: Container(
          width: 320.w,
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(16.w),
              gradient: const LinearGradient(colors: [
                Color(0xFFD2F2FF),
                Color(0xFFF5FCFF),
                Colors.white,
                Colors.white,
                Colors.white
              ], begin: Alignment.topCenter, end: Alignment.bottomCenter)),
          child: Stack(
            children: [
              Positioned(
                  top: 12.w,
                  right: 12.w,
                  child: AutoImage(
                    Assets.commonAppPackageBg,
                    width: 100.w,
                  )),
              Positioned(
                  child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    widget.appPackage.name ?? '',
                    style: TextStyle(
                        fontSize: 20.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.black),
                  ),
                  4.verticalSpaceFromWidth,
                  Text(
                    widget.appPackage.version ?? '',
                    style: TextStyle(
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.black),
                  ),
                  16.verticalSpaceFromWidth,
                  Row(
                    children: [
                      Text(
                        LocaleKeys.welcome.tr,
                        style: TextStyle(
                            fontSize: 14.sp,
                            fontWeight: FontWeight.w400,
                            color: const Color(0xFF616166)),
                      ),
                      Text(
                        AppConfig.appName,
                        style: TextStyle(
                            fontSize: 14.sp,
                            fontWeight: FontWeight.w400,
                            color: Colors.black),
                      )
                    ],
                  ),
                  12.verticalSpaceFromWidth,
                  SizedBox(
                    height: 160.w,
                    child: SingleChildScrollView(
                      child: Text(
                        widget.appPackage.note ?? '',
                        style: TextStyle(
                            fontSize: 12.sp,
                            fontWeight: FontWeight.w400,
                            color: const Color(0xFF616166)),
                      ),
                    ),
                  ),
                  32.verticalSpaceFromWidth,
                  isDownload ? _buildDownload() : _buildBottoms()
                ],
              ).marginAll(24.w))
            ],
          ),
        )));
  }

  Widget _buildBottoms() {
    return Row(
      children: [
        Visibility(
            visible: widget.appPackage.isForceUpdate != true,
            child: Expanded(
                child: CommonButton(
              title: LocaleKeys.remindLater.tr,
              enable: false,
              backgroundColors: const [
                Color(0xFFE6E6EB),
                Color(0xFFE6E6EB),
              ],
              height: 44.w,
              textColor: const Color(0xFF131313),
              alwaysCanClick: true,
              onClick: () {
                Get.back();
              },
            ).marginOnly(right: 8.w))),
        Expanded(
            child: CommonButton(
          title: (downloadFilePath ?? '').isNotEmpty
              ? LocaleKeys.reinstall.tr
              : LocaleKeys.updateNow.tr,
          height: 44.w,
          onClick: () {
            if ((downloadFilePath ?? '').isNotEmpty) {
              _installApk(downloadFilePath ?? '');
            } else {
              _startDownloadAndInstall();
            }
          },
        )),
      ],
    );
  }

  Widget _buildDownload() {
    return Column(
      children: [
        SizedBox(
          height: 12.w,
          width: double.infinity,
          child: Stack(
            children: [
              Positioned.fill(
                child: LinearProgressIndicator(
                  backgroundColor: const Color(0xFFF7F7F7),
                  value: downloadProgress,
                  borderRadius: BorderRadius.circular(10.w),
                  minHeight: 12.w,
                  color: AppColor.primary,
                ),
              ),
              Positioned.fill(
                  child: Center(
                child: Text(
                  '$downloadPercent%',
                  style: TextStyle(
                      fontSize: 8.sp,
                      fontWeight: FontWeight.w400,
                      color: Colors.black),
                ),
              )),
            ],
          ),
        ),
        15.verticalSpaceFromWidth,
        Text(
          LocaleKeys.updatingMessage.tr,
          style: TextStyle(
              fontSize: 12.sp,
              fontWeight: FontWeight.w400,
              color: Colors.black),
        ),
      ],
    );
  }
}
